package com.cis.fingerprint.controller;

import com.cis.fingerprint.core.SerialPortManager;
import com.cis.common.core.domain.AjaxResult;
import com.fazecast.jSerialComm.SerialPort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * 异步提交的请求
 */
@Controller
@RequestMapping("/opt")
public class OperationController{

    @Autowired
    SerialPortManager serialPortManager;

    private SerialPort currentPort = null;

    /**
     * 打开设备
     *
     * @param portName 串口名
     * @return 操作信息
     */
    @GetMapping("/port/open/{portName}")
    @ResponseBody
    public AjaxResult openPort(@PathVariable String portName) throws IOException {

        currentPort = serialPortManager.openDevice(portName);
        //打开串口失败
        if (null == currentPort){
            return AjaxResult.error("打开设备失败，请检查设备后重试！");
        }
        return AjaxResult.success("设备打开成功");
    }

    @GetMapping("/port/close")
    @ResponseBody
    public AjaxResult closePort(){
        if (null == currentPort){
            return AjaxResult.error("当前未打开任何设备");
        }
        if (currentPort.closePort()){
            currentPort = null;
            return AjaxResult.success("设备已关闭");
        }
        return AjaxResult.error("关闭设备失败，请检查设备后重试！");
    }

    @GetMapping("/getImage")
    @ResponseBody
    public AjaxResult getImage() throws IOException, InterruptedException {
        if(null == currentPort){
            return AjaxResult.error("请先打开设备！");
        }
        //获取指纹图像
        if (serialPortManager.getImage(currentPort)){
            return AjaxResult.success("指纹图像读取成功！");
        }
        return AjaxResult.error("指纹图像读取失败！");
    }

    @GetMapping("/storeModel")
    @ResponseBody
    public AjaxResult storeModel(Integer pId) throws IOException, InterruptedException {
        int flashId = serialPortManager.storeModel(currentPort, pId);
        if (flashId != 100 && flashId != -1) {
            AjaxResult result = new AjaxResult(AjaxResult.Type.SUCCESS, "指纹保存成功！");
            result.put("flashId", flashId);
            return result;
        }
        return AjaxResult.error("指纹保存失败！");
    }

    @GetMapping("/searchModel")
    @ResponseBody
    public AjaxResult searchModel() throws IOException, InterruptedException {
        int modelNum = serialPortManager.searchModel(currentPort);
        if (modelNum != -1) {
            AjaxResult result = new AjaxResult(AjaxResult.Type.SUCCESS, "");
            result.put("modelNum", modelNum);
            return result;
        }
        return AjaxResult.error("指纹验证失败！");
    }

}
